<template>
  <div class="batch_create">
    <el-dialog
      title="周转批次创建"
      width="80%"
      top="10%"
      max :visible.sync="dialogTableVisible"
      v-loading="createLoading || isLoading"
      v-dialogDrag
      :close-on-click-modal="false"
      customClass="mes_dialog">
      <!--<p class="form_title"><i class="iconfont icon-tishi"></i>拆分数量不能大于未拆分数量，周转数量不能大于拆分数量</p>-->
      <div class="table_dialog table_container" v-if="intoData.length">
        <el-table
          :data="formData"
          border
          class="table_dialog">
          <el-table-column
            :class-name="'static_col'"
            prop="number"
            label="工单编号"
            align="center"
            width="180"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            :class-name="'static_col'"
            prop="drawingNumber"
            label="图号"
            align="center"
            width="140"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            :class-name="'static_col'"
            prop="materialNumber"
            label="物料编码"
            align="center"
            width="140"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            :class-name="'static_col'"
            prop="materialName"
            label="物料名称"
            width="180"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            :class-name="'static_col'"
            prop="materialName"
            label="追溯要求"
            width="100"
            align="center"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{scope.row.isSingle === "Single" ? '单件追溯' : '批次追溯'}}</span>
            </template>
          </el-table-column>
          <el-table-column
            :class-name="'static_col'"
            width="110"
            prop="planQuantity"
            label="工单总数量"
            align="center"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            :class-name="'static_col'"
            width="100"
            prop="number"
            label="未拆分数量"
            align="center"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{scope.row.planQuantity-scope.row.spiltQuantity}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="number"
            label="周计划"
            align="select">
            <template slot-scope="scope">
              <el-select
                filterable
                placeholder="请选择周计划"
                v-model="scope.row.weekPlanId"
                class="type_list"
                :class="scope.row.weekPlanId ? 'error_input':''">
                <el-option
                  v-for="item in weekList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            width="100"
            prop="splitNumber"
            label="拆分数量"
            class="data_td"
            :class-name="'cell_padding'">
            <template slot-scope="scope">
              <el-input-number
                v-positive-int="{'min':1,'max':scope.row.planQuantity-scope.row.spiltQuantity}"
                v-model="scope.row.splitNumber"
                :controls="false"
                :min="1"
                :max="Number(scope.row.planQuantity-scope.row.spiltQuantity)"
                :precision="0"
                @change="splitChange(scope.row)">
              </el-input-number>
            </template>
          </el-table-column>
          <el-table-column
            width="100"
            prop="TurnoverNumber"
            :class-name="'cell_padding'"
            label="周转数量">
            <template slot-scope="scope">
              <el-input-number
                :disabled="scope.row.isSingle === 'Single'"
                v-positive-int="{'min':1,'max':scope.row.planQuantity-scope.row.spiltQuantity}"
                v-model="scope.row.TurnoverNumber"
                :controls="false"
                :min="1"
                :max="Number(scope.row.splitNumber)"
                :precision="0">
              </el-input-number>
            </template>
          </el-table-column>
          <el-table-column
            class-name="no_padding_cell"
            prop="endDate"
            :resizable="false"
            label="截止日期"
            width="180">
            <template slot-scope="scope">
              <el-date-picker
                :clearable="false"
                v-model="scope.row.endDate"
                type="date"
                placeholder="选择日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd 23:59:59"
                :picker-options="getPickerOptions(scope.row.planStartTime, scope.row.planEndTime)">
              </el-date-picker>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer mes_btn">
        <el-button type="primary" @click="createBatch()">预拆分</el-button>
        <el-button @click="dialogTableVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: 'BatchCreate',
  props: {
    intoData: Array, // 工单列表数据
  },
  data() {
    return {
      dialogTableVisible: false, // dialog组件显示、隐藏标记
      btnStatus: true, // 创建按钮disabled控制
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < this.$startTimeStamp(window.serverTime)
        }
      },
      weekList: [], // 周计划列表
      createLoading: false, // 预拆分时请求是否加载中
      isLoading: false // 周计划下拉列表请求
    }
  },
  computed: {
    // 创建工单拆分列表数据获取
    formData() {
      let formList = []
      this.intoData.map(value => {
        let obj = {
          splitNumber: value.planQuantity - value.spiltQuantity,
          TurnoverNumber: value.trackDemandValue === 'Single' ? 1 : (value.planQuantity - value.spiltQuantity),
          endDate: value.planEndTime,
          isSingle: value.trackDemandValue,
          workorder: {
            'id': value.id,
            'finalProductName': value.productName,
            'planStartTime': value.planStartTime,
            'planQuantity': value.planQuantity,
            'spiltQuantity': value.spiltQuantity,
            'number': value.number
          }
        }
        Object.assign(obj, value)
        formList.push(obj)
      })
      return formList
    },
    // 当前0点0分0秒时间戳
    todayUnix() {
      return this.$startTimeStamp(window.serverTime)
    }
  },
  methods: {
    /**
     * 切换dialog组件显示、隐藏
     * @param value
     * @returns {boolean}
     */
    switchDialog(value) {
      this.dialogTableVisible = value
      if (value) {
        this.getWeekPlanList()
      }
    },
    // 获取周计划列表
    getWeekPlanList() {
      this.isLoading = true
      this.$store.dispatch('saveData', {
        method: 'get',
        url: 'a/weekplan/weekPlan/getWeekPlanList',
        noCommit: true
      }).then((res) => {
        this.weekList = res.data
      }).finally(() => {
        this.isLoading = false
      })
    },
    // 整理工单拆分数据列表
    createBatch() {
      this.listenInput()
      if (this.btnStatus) { return false }
      let postDataList = this.formData.map(item => {
        return {
          splitNumber: Number(item.splitNumber),
          TurnoverNumber: Number(item.TurnoverNumber),
          endDate: item.endDate,
          workorderId: item.id,
          workorder: JSON.parse(JSON.stringify(item.workorder)),
          weekPlanId: item.weekPlanId,
        }
      })
      this.postCreateData({createData: postDataList, sourceData: this.intoData})
    },
    /**
     * 预拆分请求
     * @param obj 预拆分前置、请求数据
     */
    postCreateData(obj) {
      this.createLoading = true
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/workorder/workorder/prepareSplit',
        data: { 'dataArray': obj.createData },
        noCommit: true
      }).then((res) => {
        obj.response = res.data
        this.$emit('createSuccess', obj)
        this.dialogTableVisible = false
      }).finally(() => {
        this.createLoading = false
      })
    },
    /**
     * 拆分数量变化
     * @param row 当前行数据
     */
    splitChange(row) {
      if (row.TurnoverNumber > row.splitNumber) {
        row.TurnoverNumber = 0
      }
    },
    /**
     * 监听拆分数和周转数输入框，输入数值是否符合拆分规则
     */
    listenInput() {
      if (this.formData.length > 0) {
        if (this.formData.some((item) => !item.splitNumber)) {
          this.btnStatus = true
          return this.errorMessage('拆分数量不能为空')
        }
        if (this.formData.some((item) => !item.TurnoverNumber)) {
          this.btnStatus = true
          return this.errorMessage('周转数量不能为空')
        }
        if (this.formData.some((item) => !item.endDate)) {
          this.btnStatus = true
          return this.errorMessage('请选择截止日期')
        }
        if (this.formData.some((item) => Number(item.TurnoverNumber) > Number(item.splitNumber))) {
          this.btnStatus = true
          return this.errorMessage('周转数量不能大于拆分数量')
        }
        if (this.formData.find((item) => {
          let num = item.planQuantity - item.spiltQuantity
          if (item.splitNumber > num) {
            return item
          }
        })) {
          this.btnStatus = true
          return this.errorMessage('拆分数量不能大于未拆分数量')
        }
      }
      this.btnStatus = false
    },
    getPickerOptions(start, end) {
      let self = this
      return {
        disabledDate(time) {
          if (self.moment(self.todayUnix).isBefore(start)) {
            return time.getTime() < self.$startTimeStamp(start) || time.getTime() > self.$endTimeStamp(end)
          } else {
            return time.getTime() < self.todayUnix || time.getTime() > self.$endTimeStamp(end)
          }
        }
      }
    },
    /**
     * 错误提示
     * @param str 提示内容
     */
    errorMessage(str) {
      this.$message({
        type: 'error',
        message: str,
        duration: 1500,
        center: true
      })
    }
  }
}
</script>

<style lang="less">
  .batch_create {
    .table_container{
      margin-right: 2px;
    }
    td .cell {
      height: 40px;
      .el-input__inner {
        position: absolute;
        top: 0;
        left: 0;
        &.error_input {
          color: @mesTableInputEFC;
        }
        &:focus {
          border: @mesTableInputFBorder;
        }
      }
      .is-disabled input{
        background-color: #f5f5f5 !important;
      }
      .type_list{
        width: 100%;
        height: 100%;
      }
    }
    td.static_col{
      background-color: @mesNoEditableBg !important;
    }
    .el-table__body, .el-table__header {
      border-left: @mesBorDefault;
    }
    .el-table--enable-row-hover .el-table__body tr:hover > td {
      background-color: @mesBgWhite;
    }
    .no_padding_cell{
      .cell{
        padding: 0;
      }
    }
  }
</style>
